from image_process.noise_manage import events_to_count_image_single, create_noise_mask, apply_noise_mask
from image_process.eyelid_glint import create_eyelid_glint_mask
from image_process.eyelash import create_eyelash_mask
from image_process.pupil_center import generate_donut_kernel
from scipy.signal import fftconvolve
from image_process.ellipse_fit import fit_ellipse, ellipse_fit_score
from image_process.pupil_center import locate_pupil_center, create_pupil_mask
import numpy as np

def image_process(event_list, min_score):
    """
    对事件流进行瞳孔椭圆拟合的完整处理流程。
    参数:
        event_list (list): 包含2000个事件的一维列表 [p1, r1, c1, t1, ...]。
        min_score (float): 椭圆拟合分数的最小阈值，低于该值则认为拟合失败。
    返回:
        ellipse (tuple or None): 拟合成功时返回椭圆参数 (xc, yc, a, b, theta)，否则返回 None。
    """    
    pos_img, neg_img = events_to_count_image_single(event_list)
    noise_mask = create_noise_mask(pos_img, neg_img)
    pos_img_denoised, neg_img_denoised = apply_noise_mask(pos_img, neg_img, noise_mask)
    eyelid_glint_mask = create_eyelid_glint_mask(pos_img_denoised, neg_img_denoised, 
                         bin_thresh=1, dilate_kernel=7, dilate_shape='ellipse', 
                         expand_kernel=5, expand_shape='ellipse')
    eyelash_mask = create_eyelash_mask(pos_img + neg_img, eyelid_glint_mask, 
                                    blur_ksize=3, blur_thresh=1,
                                    morph_ksize1=11, morph_ksize2=5, morph_rect_w=21, morph_rect_h=9)
    
    iris_mask = (noise_mask | eyelid_glint_mask | eyelash_mask)
    pos_img_iris, neg_img_iris = apply_noise_mask(pos_img, neg_img, iris_mask)
    iris_img = (pos_img_iris + neg_img_iris) > 0
    
    bandwidth = 32
    kernel = generate_donut_kernel(inner_radius=bandwidth//2, outer_radius=bandwidth)
    density_map = fftconvolve(iris_img, kernel, mode='same')
    center_y, center_x = np.unravel_index(np.argmax(density_map), density_map.shape)
    
    center_y, center_x = locate_pupil_center(iris_img, bandwidth)
    pupil_mask = create_pupil_mask(iris_img, (center_x, center_y), bandwidth)
    
    pos_img_pupil, neg_img_pupil = apply_noise_mask(pos_img_iris, neg_img_iris, ~pupil_mask)
    
    pupil_img = (pos_img_pupil + neg_img_pupil) > 0
    points_y, points_x = np.where(pupil_img)
    pupil_points = np.column_stack((points_x, points_y))

    ellipse = fit_ellipse(pupil_points)
    
    fit_score = 0.
    if ellipse is not None:
        fit_score = ellipse_fit_score(pupil_points, ellipse)
    
    if fit_score >= min_score:
        return ellipse
    else:
        return None
    